// this file allows you to save an image to a file. 
// there is a place where you could take the image data in RGB and do something else with it.
// image_handler.c
//
// To compile:
//
// gcc -o decode_video decode_video.c -lavutil -lavformat -lavcodec -lz -lavutil -lm
//

#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/mathematics.h"

#include <stdio.h>
#include <stdlib.h>

void imageHandler(AVFrame *pFrame, int width, int height, int Frame, char *filename)
{
  SaveFrame(pFrame, width, height, Frame, filename);
  //if you want to use the image data for something else, delete this call, and write your own function.
}

void SaveFrame(AVFrame *pFrame, int width, int height, int Frame, char *filename)
{
    FILE *pFile;
    char tempfilename[128];
    char picfilename[128];
    char num_buf[10];
    int  y;
    char *ptr;


    // Open file
    strcpy(tempfilename, "output/");
    strcat(tempfilename, filename);
    ptr = strrchr(tempfilename, '.');
    if (ptr != 0) *ptr = 0;       // remove file extension from filename
    strcpy(picfilename, tempfilename);
    sprintf(num_buf, "_%d", Frame);
    strcat(picfilename, num_buf);
    strcat(picfilename, ".ppm");

    pFile=fopen(picfilename, "wb");
    if(pFile==NULL)
        return;

    // Write header
    fprintf(pFile, "P6\n%d %d\n255\n", width, height);

    // Write pixel data
    for(y=0; y<height; y++)
        fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);

    // Close file
    fclose(pFile);
}


